<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996 15899929162
// +----------------------------------------------------------------------
namespace app\common\dao\energy;

use app\common\dao\BaseDao;
use app\common\model\energy\EnergyBillModel;

class EnergyBillDao extends BaseDao
{

    /**
     * @return EnergyBillModel
     */
    protected function getModel(): string
    {
        return EnergyBillModel::class;
    }


    public function search(array $where, int $propertyId = null)
    {
        return $this->getModel()::getDB()
            ->when($propertyId !== null, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['contract_id']) && $where['contract_id'] !== '', function ($query) use ($where) {
                $query->where('contract_id', intval($where['contract_id']));
            })
            ->when(isset($where['energy_type']) && $where['energy_type'] !== '', function ($query) use ($where) {
                $query->where('energy_type', intval($where['energy_type']));
            })
            ->when(isset($where['energy_id']) && $where['energy_id'] !== '', function ($query) use ($where) {
                $query->where('energy_id', intval($where['energy_id']));
            })
            ->when(isset($where['room_id']) && $where['room_id'] !== '', function ($query) use ($where) {
                $query->where('room_id', intval($where['room_id']));
            })
            ->when(isset($where['energy_no']) && $where['energy_no'] !== '', function ($query) use ($where) {
                $query->whereIn('energy_id', function ($query) use ($where) {
                    $query->name('energy_meter')->where('energy_no', $where['energy_no'])->field('id');
                });
            })
            ->when(isset($where['keywords']) && $where['keywords'] !== '', function ($query) use ($where) {
                $query->whereLike('energy_name|remark', '%' . trim($where['keywords']) . '%');
            });
    }

    /**
     *  根据 设备 ID 删除记录
     * @param int $energyId
     * @return bool
     *
     * @author Amos
     * 2024-05-09 20:56
     */
    public function removeMeterId(int $energyId)
    {
        return $this->getSearch([
            'energy_id' => $energyId,
        ])->delete();
    }
}
